/**
 * Copyright (C), 2015-2022, 成都启迪信息技术有限公司
 * FileName: GasHttpServiceInitApplicationContextAware
 * Author:   sjk
 * Date:     2022-10-18 16:03
 * Description:
 * <author>          <time>          <version>          <desc>
 * 作者姓名         修改时间           版本号            描述
 */
package com.qd.panda.gas.station.base;

import com.cdqidi.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 加油接口初始化
 *
 * @author sjk
 * @create 2022-10-18 16:03
 * @since 1.0.0
 */
@Component
@Slf4j
public class GasHttpServiceInitApplicationContextAware implements ApplicationContextAware {
    private static final Map<String, GasHttpService> GAS_HTTP_SERVICE_MAP = new HashMap<>(16);

    @Override
    public void setApplicationContext(@NotNull ApplicationContext applicationContext) throws BeansException {
        log.info("加油接口初始化");
        final Map<String, GasHttpService> beansOfType = applicationContext.getBeansOfType(GasHttpService.class);
        beansOfType.forEach((key, value) -> {
            log.info("加油站公司名称: {},实现类: {}", value.stationCompanyId(), value.getClass());
            GAS_HTTP_SERVICE_MAP.put(value.stationCompanyId(), value);
        });
    }

    @SuppressWarnings("unchecked")
    public static <T extends GasHttpService> T getGasHttpService(String stationCompanyId) {
        final GasHttpService gasHttpService = GAS_HTTP_SERVICE_MAP.get(stationCompanyId);
        if (null == gasHttpService) {
            throw new ApiException("当前加油站未注册: " + stationCompanyId);
        }
        return (T) gasHttpService;
    }
}